//
//  PopoverView.m
//  ArrowView
//
//  Created by guojiang on 4/9/14.
//  Copyright (c) 2014年 LINAICAI. All rights reserved.
//

// 版权属于原作者
// http://code4app.com (cn) http://code4app.net (en)
// 发布代码于最专业的源码分享网站: Code4App.com

#import "PopoverView1.h"


#define kArrowHeight 10.f
#define kArrowCurvature 6.f
#define SPACE 10.f
#define ROW_HEIGHT 36.f
#define TITLE_FONT [UIFont systemFontOfSize:13]
#define RGB(r, g, b)    [UIColor colorWithRed:(r)/255.f green:(g)/255.f blue:(b)/255.f alpha:1.f]

@interface PopoverView1 ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) NSArray *titleArray;
@property (nonatomic, strong) NSArray *imageArray;


@property (nonatomic, strong) NSMutableArray *titleRightArray;
@property (nonatomic, strong) NSMutableArray *imageRightArray;

@property (nonatomic, strong) NSString *keyStr;




@property (nonatomic) CGPoint showPoint;

@property (nonatomic, strong) UIButton *handerView;

@end

@implementation PopoverView1

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        self.borderColor = RGB(200, 199, 204);
        self.backgroundColor = [UIColor clearColor];
        
    }
    return self;
}

-(id)initWithPoint:(CGPoint)point titles:(NSArray *)titles images:(NSArray *)images titleAndImageRightDict:(NSMutableDictionary *)titleAndImageRightDict
{
    self = [super init];
    if (self) {
        self.showPoint = point;
        self.titleArray = titles;
        self.imageArray = images;
        self.titleAndImageRightDict=titleAndImageRightDict;
        self.keyStr = [[NSString alloc]initWithFormat:@"%@",[self.titleArray objectAtIndex:0] ];
        _titleRightArray = [[self.titleAndImageRightDict objectForKey:self.keyStr] objectForKey:@"title"];
        _imageRightArray = [[self.titleAndImageRightDict objectForKey:self.keyStr] objectForKey:@"image"];
        
        
        
        self.frame = [self getViewFrame];
        
        [self addSubview:self.tableView];
        self.titleAndImageRightDict = titleAndImageRightDict;
        [self addSubview:self.viewRight];

        
        
    }
    return self;
}
-(void)setTitleAndImageRightDict:(NSMutableDictionary *)titleAndImageRightDict index:(NSInteger)index{
    _titleAndImageRightDict =titleAndImageRightDict;
    self.keyStr = [[NSString alloc]initWithFormat:@"%@",[self.titleArray objectAtIndex:index] ];
    
    _titleRightArray = [[self.titleAndImageRightDict objectForKey:self.keyStr] objectForKey:@"title"];
    _imageRightArray = [[self.titleAndImageRightDict objectForKey:self.keyStr] objectForKey:@"image"];
    
    [_tableViewRight reloadData];

//    [self addSubview:self.viewRight];

}

-(CGRect)getViewFrame
{
    CGRect frame = CGRectZero;
    
    frame.size.height = [self.titleArray count] * ROW_HEIGHT + 2*SPACE + kArrowHeight;
    
    for (NSString *title in self.titleArray) {
//        CGFloat width =  [title sizeWithFont:TITLE_FONT constrainedToSize:CGSizeMake(300, 100) lineBreakMode:NSLineBreakByCharWrapping].width;
        CGFloat width =  220;

        frame.size.width = MAX(width, frame.size.width);
    }
    
    if ([self.titleArray count] == [self.imageArray count]) {
        frame.size.width = kScreenWidth;
    }else{
        frame.size.width = kScreenWidth;
    }
    
    frame.origin.x = self.showPoint.x - frame.size.width/2;
    frame.origin.y = self.showPoint.y;
    
    //左间隔最小5x
    if (frame.origin.x < 5) {
        frame.origin.x = 0;
    }
    //右间隔最小5x
    if ((frame.origin.x + frame.size.width) > kScreenWidth-5) {
        frame.origin.x = 0;
    }
    
    return frame;
}


-(void)show
{
    
    self.handerView = [UIButton buttonWithType:UIButtonTypeCustom];
    [_handerView setFrame:[UIScreen mainScreen].bounds];
    [_handerView setBackgroundColor:[UIColor clearColor]];

    [_handerView addTarget:self action:@selector(dismiss) forControlEvents:UIControlEventTouchUpInside];
    [_handerView addSubview:self];
//    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    
    [[[UIApplication sharedApplication].delegate window] addSubview:_handerView];
    
    CGPoint arrowPoint = [self convertPoint:self.showPoint fromView:_handerView];
    self.layer.anchorPoint = CGPointMake(arrowPoint.x / self.frame.size.width, arrowPoint.y / self.frame.size.height);
    self.frame = [self getViewFrame];
    
    self.alpha = 0.f;
    self.transform = CGAffineTransformMakeScale(0.1f, 0.1f);
//    [UIView animateWithDuration:0.2f delay:0.f options:UIViewAnimationOptionCurveEaseInOut animations:^{
        self.transform = CGAffineTransformMakeScale(1.05f, 1.05f);
        self.alpha = 1.f;
//    } completion:^(BOOL finished) {
//        [UIView animateWithDuration:0.08f delay:0.f options:UIViewAnimationOptionCurveEaseInOut animations:^{
            self.transform = CGAffineTransformIdentity;
//        } completion:nil];
//    }];
    
    UIButton *viewb = [[UIButton alloc]initWithFrame:CGRectMake(self.frame.origin.x,self.frame.size.height+self.frame.origin.y, kScreenWidth,kScreenHeight-self.frame.size.height-self.frame.origin.y-49)];
    [viewb addTarget:self action:@selector(dismiss) forControlEvents:UIControlEventTouchUpInside];
    [viewb setBackgroundColor:[UIColor colorWithRed:0 green:0 blue:0 alpha:0.5]];
    [_handerView addSubview:viewb];

    
}

-(void)dismiss
{
    [self dismiss:YES];
}

-(void)dismiss:(BOOL)animate
{
    if (!animate) {
        [_handerView removeFromSuperview];
        return;
    }
    
//    [UIView animateWithDuration:0.3f animations:^{
        self.transform = CGAffineTransformMakeScale(0.1f, 0.1f);
        self.alpha = 0.f;
//    } completion:^(BOOL finished) {
        [_handerView removeFromSuperview];
//    }];
    
}


#pragma mark - UITableView

-(UITableView *)tableView
{
    if (_tableView != nil) {
        return _tableView;
    }
    
//    CGRect rect = self.frame;
    CGRect rect = CGRectMake(10, self.frame.origin.y, kScreenWidth/4*2, self.frame.size.height);

    rect.origin.x = 0;
    rect.origin.y = kArrowHeight + SPACE;
    rect.size.width -= SPACE * 2;
//    rect.size.height -= (SPACE - kArrowHeight)-20;
    rect.size.height -= (3*SPACE);
    
    self.tableView = [[UITableView alloc] initWithFrame:rect style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.alwaysBounceHorizontal = NO;
    _tableView.alwaysBounceVertical = NO;
    _tableView.showsHorizontalScrollIndicator = NO;
    _tableView.showsVerticalScrollIndicator = NO;
    _tableView.scrollEnabled = NO;
    _tableView.backgroundColor = [UIColor redColor];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;

//    _tableView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    
    return _tableView;
}

#pragma mark - UITableView DataSource

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSInteger numbers=0;
    if (tableView==_tableView) {
        numbers = [_titleArray count];
    }else if (tableView==_tableViewRight) {
        numbers = [[[self.titleAndImageRightDict objectForKey:self.keyStr] objectForKey:@"title"]count];

    }
    
    return numbers;
}
-(UIImage *)imageFromImage:(UIImage *)image inRect:(CGRect)rect {
    CGImageRef sourceImageRef = [image CGImage];
    CGImageRef newImageRef = CGImageCreateWithImageInRect(sourceImageRef, rect);
    UIImage *newImage = [UIImage imageWithCGImage:newImageRef];
    return newImage;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[PopoverView1TableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    
    cell.textLabel.textColor = TITLE_ARTICLE_TEXTFONT_COLOR;
    
    if (tableView==_tableView) {
        cell.backgroundView = [[UIView alloc] init];
        cell.backgroundView.backgroundColor = [ClassMethodsViewController colorWithHexString:LEFT_BACKCOLOR_16];
        
        if ([_imageArray count] == [_titleArray count]) {

//            cell.imageView.image = [UIImage imageNamed:[_imageArray objectAtIndex:indexPath.row]];
//            [cell.imageView setImageURLStr:[NSString stringWithFormat:@"%@",[_imageArray objectAtIndex:indexPath.row]] placeholder:nil];
            

            
            
            
            
            NSMutableString *picName = [[NSMutableString alloc]init];

            
            NSString *searchstring=[NSString stringWithFormat:@"%@",[_imageArray objectAtIndex:indexPath.row]];
            
            
            NSRange aa=[searchstring rangeOfString:@"/"];
            if (aa.location != NSNotFound) {
                NSArray *arr = [[NSArray alloc]initWithArray:[searchstring componentsSeparatedByString:@"/"]];
                for (int i=0;i<arr.count;i++) {
                    [picName appendString:[arr objectAtIndex:i]];
                    if (i!=arr.count-1) {
                        [picName appendString:@"-"];
                        
                    }
                    
                }
            }else{
                [picName appendString:searchstring];
            }
            
            

            NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
            // 2.2.获得文件的全路径
            NSString *path = [doc stringByAppendingPathComponent:[NSString stringWithFormat:@"%@",picName]];
            NSFileManager *fileManager = [NSFileManager defaultManager];

            
            
            
//            if (![fileManager fileExistsAtPath:path]) {//没文件的情况
            
            UIImageView *imageview = [[UIImageView alloc]initWithFrame:CGRectMake(10, 10,20, 20)];
                
                
                
                imageview.layer.cornerRadius = 10;
                imageview.layer.masksToBounds = YES;
                
                __block UIImageView *blockSelf = imageview;
                [imageview setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",[_imageArray objectAtIndex:indexPath.row]]] placeholderImage:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType) {
                    
                    
                    
                    CGRect range = CGRectMake(0, 0,image.size.height, image.size.height);
                    UIImage *im2 = [self imageFromImage:image inRect:range];
                    
                    [fileManager createFileAtPath:path contents:nil attributes:nil];
                    [[SDImageCache sharedImageCache] storeImage:im2 forKey:[NSString stringWithFormat:@"%@",picName]];//图片保存到本地
                    
                    
                    [cell.imageView removeFromSuperview];
                    CGRect range1 = CGRectMake(0, 0,image.size.height, image.size.height);
                    blockSelf.image = [self imageFromImage:image inRect:range1];
                    
                    [cell addSubview:blockSelf];
                    
                    
                }];
                
                
                
//            }else{
//                
//                
//                UIImage *im = [[SDImageCache sharedImageCache] imageFromDiskCacheForKey:[NSString stringWithFormat:@"%@",picName]];
//                CGRect range = CGRectMake(0, 0,im.size.height, im.size.height);
//               UIImage *im2 = [self imageFromImage:im inRect:range];
//                cell.imageView.image =im2;
//                
//            }
            
            UIView *view = [[UIView alloc]initWithFrame:CGRectMake(tableView.frame.size.width-1, 0, 1, cell.frame.size.height)];
            view.backgroundColor = [ClassMethodsViewController colorWithHexString:@"#cccccc"];
            [cell.contentView addSubview:view];
            
        }
        cell.textLabel.font = TITLE_FONT;
        cell.textLabel.text = [_titleArray objectAtIndex:indexPath.row];
        
        if ([[UIDevice currentDevice].systemVersion floatValue] >= 7.0) {

            cell.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0);
        }
        cell.selectedBackgroundView = [[UIView alloc] initWithFrame:cell.frame];
        cell.selectedBackgroundView.backgroundColor = [ClassMethodsViewController colorWithHexString:LEFT_SELECT_BACKCOLOR];


    }else if (tableView==_tableViewRight) {
        cell.backgroundView = [[UIView alloc] init];
        cell.backgroundView.backgroundColor = [ClassMethodsViewController colorWithHexString:LEFT_SELECT_BACKCOLOR];
        
        if ([_imageRightArray count] == [_titleRightArray count]) {
//            cell.imageView.frame = CGRectMake(0, 0, 21, 20);
//
//            cell.imageView.image = [UIImage imageNamed:[_imageRightArray objectAtIndex:indexPath.row]];
            
            
            [cell.imageView setImageURLStr:[NSString stringWithFormat:@"%@",[_imageRightArray objectAtIndex:indexPath.row]] placeholder:nil];

        }
        cell.textLabel.font = TITLE_FONT;
        cell.textLabel.text = [_titleRightArray objectAtIndex:indexPath.row];
        
        if ([[UIDevice currentDevice].systemVersion floatValue] >= 7.0) {
            cell.separatorInset = UIEdgeInsetsMake(0, 50, 0, 0);
        }
        cell.selectedBackgroundView = [[UIView alloc] initWithFrame:cell.frame];
        cell.selectedBackgroundView.backgroundColor = [UIColor clearColor];
//        cell.selectionStyle =UITableViewCellSelectionStyleNone;
        
        
        
//        cell.textLabel.textAlignment = NSTextAlignmentCenter;
        
    }
    cell.textLabel.textColor = [ClassMethodsViewController colorWithHexString:TEXT_COLOR];
    cell.textLabel.highlightedTextColor =[ClassMethodsViewController colorWithHexString:SELECT_BORDERCOLOR];
    return cell;
}

#pragma mark - UITableView Delegate

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    


    

    if (tableView==_tableView) {
        if (self.selectRowAtIndex) {
            self.selectRowAtIndex(indexPath.row);
            self.keyStr = [[NSString alloc]initWithFormat:@"%@",[self.titleArray objectAtIndex:indexPath.row] ];
            
            _titleRightArray = [[self.titleAndImageRightDict objectForKey:self.keyStr] objectForKey:@"title"];
            _imageRightArray = [[self.titleAndImageRightDict objectForKey:self.keyStr] objectForKey:@"image"];
            
            [_tableViewRight reloadData];
            
            
            
        }
    }else if (tableView==_tableViewRight) {
        [tableView deselectRowAtIndexPath:indexPath animated:YES];


        if (self.selectRowAtRightIndex) {
            self.selectRowAtRightIndex(indexPath.row);
            
            [tableView deselectRowAtIndexPath:indexPath animated:NO];
            [self dismiss:YES];
            
        }
        
    }
    
    
//    [tableView deselectRowAtIndexPath:indexPath animated:NO];
  //    [self dismiss:YES];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return ROW_HEIGHT;
}



// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    [self.borderColor set]; //设置线条颜色
    
    CGRect frame = CGRectMake(0, 10, self.bounds.size.width, self.bounds.size.height - kArrowHeight);
    
    float xMin = CGRectGetMinX(frame);
    float yMin = CGRectGetMinY(frame);
    
    float xMax = CGRectGetMaxX(frame);
    float yMax = CGRectGetMaxY(frame);
    
    CGPoint arrowPoint = [self convertPoint:self.showPoint fromView:_handerView];
    
    UIBezierPath *popoverPath = [UIBezierPath bezierPath];
    [popoverPath moveToPoint:CGPointMake(xMin, yMin)];//左上角
    
    /********************向上的箭头**********************/
    
    
    
    
    [popoverPath addLineToPoint:CGPointMake(arrowPoint.x - kArrowHeight, yMin)];//left side
//    [popoverPath addLineToPoint:arrowPoint];

    [popoverPath addLineToPoint:CGPointMake(arrowPoint.x  - kArrowCurvature, yMin)];
    [popoverPath addLineToPoint:arrowPoint];
    [popoverPath addLineToPoint:CGPointMake(arrowPoint.x + kArrowCurvature, yMin)];
    
//    [popoverPath addCurveToPoint:arrowPoint
//                   controlPoint1:CGPointMake(arrowPoint.x - kArrowHeight + kArrowCurvature, yMin)
//                   controlPoint2:arrowPoint];//actual arrow point
//    
//    [popoverPath addCurveToPoint:CGPointMake(arrowPoint.x + kArrowHeight, yMin)
//                   controlPoint1:arrowPoint
//                   controlPoint2:CGPointMake(arrowPoint.x + kArrowHeight - kArrowCurvature, yMin)];//right side
    /********************向上的箭头**********************/
    
    
    [popoverPath addLineToPoint:CGPointMake(xMax, yMin)];//右上角
    
    [popoverPath addLineToPoint:CGPointMake(xMax, yMax)];//右下角
    
    [popoverPath addLineToPoint:CGPointMake(xMin, yMax)];//左下角
    
    //填充颜色
//    [RGB(113, 113, 113) setFill];
    [[ClassMethodsViewController colorWithHexString:LEFT_BACKCOLOR_16] setFill];
    [popoverPath fill];
    
    [popoverPath closePath];
//    [popoverPath stroke];
}

-(UITableView *)tableViewRight{
    if (_tableViewRight != nil) {
        return _tableViewRight;
    }
    CGRect rect = CGRectMake(_tableView.frame.size.width+_tableView.frame.origin.x, _tableView.frame.origin.y, _tableView.superview.frame.size.width-_tableView.frame.size.width, _tableView.superview.frame.size.height-_tableView.frame.origin.y+SPACE);

    
    rect.origin.x = _tableView.frame.size.width+_tableView.frame.origin.x;
    rect.origin.y = _tableView.frame.origin.y-SPACE;
//    rect.size.width -= SPACE * 4;
//    rect.size.height =rect.size.height-(SPACE - kArrowHeight)*2;
    
    
    UIView *view = [[UIView alloc]initWithFrame:rect];
    view.backgroundColor = [ClassMethodsViewController colorWithHexString:LEFT_SELECT_BACKCOLOR];
    
    
    self.tableViewRight = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, rect.size.width, rect.size.height) style:UITableViewStylePlain];
    
    _tableViewRight.delegate = self;
    _tableViewRight.dataSource = self;
    _tableViewRight.alwaysBounceHorizontal = NO;
    _tableViewRight.alwaysBounceVertical = NO;
    _tableViewRight.showsHorizontalScrollIndicator = NO;
    _tableViewRight.showsVerticalScrollIndicator = NO;
//    _tableViewRight.scrollEnabled = NO;
    _tableViewRight.backgroundColor = [UIColor clearColor];
    _tableViewRight.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    NSIndexPath *first = [NSIndexPath indexPathForRow:0 inSection:0];
    
    [_tableView selectRowAtIndexPath:first animated:YES scrollPosition:UITableViewScrollPositionTop];
    
    
    
    UIView *viewHeader = [[UIView alloc]initWithFrame:CGRectMake(0, 0, _tableViewRight.frame.size.width, 10)];
    viewHeader.backgroundColor = [ClassMethodsViewController colorWithHexString:LEFT_SELECT_BACKCOLOR];

    
    
    _tableViewRight.tableHeaderView = viewHeader;
    //没被选择的右边线条
    UIView *view1 = [[UIView alloc]initWithFrame:CGRectMake(self.tableView.frame.size.width-1, self.tableView.frame.origin.y-SPACE, 1, SPACE)];
    view1.backgroundColor = [ClassMethodsViewController colorWithHexString:@"#cccccc"];
    [self addSubview:view1];
    
    UIView *view2 = [[UIView alloc]initWithFrame:CGRectMake(self.tableView.frame.size.width-1, self.tableView.frame.origin.y+self.tableView.frame.size.height, 1, self.frame.size.height-(self.tableView.frame.origin.y+self.tableView.frame.size.height))];
    view2.backgroundColor = [ClassMethodsViewController colorWithHexString:@"#cccccc"];
    [self addSubview:view2];
    
    
    return _tableViewRight;
}
-(UIView *)viewRight{
    if (_tableViewRight != nil) {
        return _tableViewRight;
    }
    CGRect rect = CGRectMake(_tableView.frame.size.width+_tableView.frame.origin.x, _tableView.frame.origin.y, _tableView.superview.frame.size.width-_tableView.frame.size.width, _tableView.superview.frame.size.height-_tableView.frame.origin.y+SPACE);
    
    
    rect.origin.x = _tableView.frame.size.width+_tableView.frame.origin.x;
    rect.origin.y = _tableView.frame.origin.y-SPACE;
    //    rect.size.width -= SPACE * 4;
    //    rect.size.height =rect.size.height-(SPACE - kArrowHeight)*2;
    
    
    _viewRight = [[UIView alloc]initWithFrame:rect];
    _viewRight.backgroundColor = [ClassMethodsViewController colorWithHexString:LEFT_SELECT_BACKCOLOR];
    
    [_viewRight addSubview:self.tableViewRight];
    return _viewRight;
}
@end
